package com.poetize.plus.validator;

import com.poetize.plus.annotation.Secret;
import com.poetize.plus.enums.AlgorithmEnum;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;

/**
 *
 * 密钥注解处理器
 *
 * @author zuosy
 * @created 2024/3/28 15:28
 */
public class SecretValidator implements ConstraintValidator<Secret, String> {

    @Value("${security.jwt.algorithm}")
    private AlgorithmEnum algorithm;

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (!StringUtils.hasText(s)){
            constraintValidatorContext.disableDefaultConstraintViolation();
            constraintValidatorContext.buildConstraintViolationWithTemplate("密钥不能为空").addConstraintViolation();
            return false;
        }
        if (s.length() < algorithm.getLength()){
            constraintValidatorContext.disableDefaultConstraintViolation();
            constraintValidatorContext.buildConstraintViolationWithTemplate("密钥长度不能低于" + algorithm.getLength() + "字节").addConstraintViolation();
            return false;
        }
        return true;
    }

}
